package com.thrc.borrow.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import com.alibaba.druid.util.StringUtils;

public class CacheUtil {

	private static Map<String, CacheObj> cacheMap = new HashMap<String, CacheObj>();

	private static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

	public static void setCacheDate(String key, Object data) {

		if (atomicBoolean.compareAndSet(false, true)) {
			cacheMap.put(key, new CacheObj(data));
			atomicBoolean.set(false);
		}

	}

	@SuppressWarnings("unchecked")
	public static <T> T getCacheDate(String key, Class<T> t) {

		if (StringUtils.isEmpty(key))
			return null;

		CacheObj obj = cacheMap.get(key);
		if (obj == null)
			return null;

		return (T) obj.getCacheObj();
	}

	public static class CacheObj {

		public CacheObj(Object cacheObj) {
			this.timestamp = System.currentTimeMillis();
			this.cacheObj = cacheObj;
		}

		private long timestamp = 0l;
		private Object cacheObj = null;

		public long getTimestamp() {
			return timestamp;
		}

		public void setTimestamp(long timestamp) {
			this.timestamp = timestamp;
		}

		public Object getCacheObj() {
			return cacheObj;
		}

		public void setCacheObj(Object cacheObj) {
			this.cacheObj = cacheObj;
		}

	}
}
